<template>
  <view>
    <view class="flex justify-between items-center py-8 px-12">
      <view
        >全部<text class="ml-4 color-primary">{{ cartInfo.total }}</text>
      </view>
      <view class="w-64">
        <u-button
          v-if="!isEdit"
          text="编辑"
          shape="circle"
          @click="isEdit = true"
        ></u-button>
        <u-button
          v-else
          text="取消"
          shape="circle"
          @click="isEdit = false"
        ></u-button>
      </view>
    </view>
    <view v-if="cartList.length">
      <u-checkbox-group
        v-model="checked"
        @change="onCheckItem"
        placement="column"
      >
        <view
          class="flex goods-card p-12"
          v-for="(item, index) in cartList"
          :key="index"
        >
          <view class="flex items-center">
            <u-checkbox
              :name="item.serialNo"
              shape="circle"
              active-color="#6eca96"
            >
            </u-checkbox>
            <u-image
              width="180rpx"
              height="180rpx"
              :src="item.coverImage"
            ></u-image>
          </view>

          <view class="pl-12 flex-1">
            <view class="ellipsis-2 color-black">{{ item.goodsName }}</view>

            <!--            <template v-if="item.goodsSkuInfo">-->
            <!--              <view class="text-12">-->
            <!--                {{ item.goodsSkuInfo.skuText }}-->
            <!--              </view>-->
            <!--              <view class="ellipsis-2 color-tip pt-8 text-14">{{-->
            <!--                item.quantity-->
            <!--              }}</view>-->
            <!--            </template>-->
            <view
              class="spec-box flex items-center color-gray mt-12 text-14 border-box px-12 justify-between"
            >
              <view>{{
                item.goodsSkuInfo ? item.goodsSkuInfo.skuText : "暂无规格"
              }}</view>
              <u-icon
                v-if="item.goodsSkuInfo"
                name="arrow-down"
                size="30rpx"
              ></u-icon>
            </view>
            <view
              class="text-red text-18 flex justify-between items-center mt-12"
            >
              <view>
                <text class="text-14">￥</text>
                <text>{{ item.price }}</text></view
              >
              <u-number-box v-model="item.quantity"></u-number-box>
            </view>
          </view>
        </view>
      </u-checkbox-group>
    </view>
    <u-empty
      v-else
      :mode="mode"
      icon="http://cdn.uviewui.com/uview/empty/car.png"
      marginTop="35%"
    >
      <u-button
        size="small"
        type="primary"
        class="mt-4"
        text="去选择商品"
        @click="onHome"
      >
      </u-button>
    </u-empty>
    <!-- <view class="invalidGoods mt-12" v-if="deadlineList.length">
			<view class="flex justify-between p-12">
				<view class="text-16">失效商品</view>
				<view class="text-red text-14" @click="onRemoveDeadline">清空已失效宝贝</view>
			</view>
			<view class="flex goods-card p-12" v-for="(item,index) in deadlineList" :key="index">
				<view class="flex items-center">
					<u-image width="180rpx" height="180rpx"></u-image>
				</view>

				<view class="pl-12">
					<view class="ellipsis-2 color-tip">{{item.goodsName}}</view>
				</view>
			</view>
		</view> -->

    <u-tabbar>
      <view
        class="address-div flex justify-start text-12"
        @click="selectShopAddress"
      >
        <view class="flex items-center">
          <u-icon name="map-fill" size="24rpx" color="#1f1f1f"></u-icon>
          <view class="ml-4 u-line-1 mr-4">
            {{ address.detailAddress ? "已选择收货地址" : "请选择收货地址" }}
          </view>
          <u-icon
            v-if="address.detailAddress"
            name="checkmark-circle-fill"
            size="24rpx"
            color="#6eca96"
          ></u-icon>
        </view>
      </view>
      <view class="flex items-center w-full border-box px-12 justify-between">
        <view class="flex items-center">
          <u-checkbox-group v-model="checkedAll" @change="onCheckAll">
            <u-checkbox
              label="全选"
              :name="true"
              shape="circle"
              active-color="#6eca96"
            >
            </u-checkbox>
          </u-checkbox-group>
          <view class="ml-8">
            <text>合计</text>
            <text class="text-red">￥</text>
            <text class="text-red">{{ totalAmount }}</text>
          </view>
        </view>
        <view>
          <u-button
            v-if="isEdit"
            text="删除"
            type="error"
            shape="circle"
            @click="onRemove"
          ></u-button>
          <u-button
            v-else
            text="去结算"
            type="primary"
            shape="circle"
            @click="onConfirm"
          ></u-button>
        </view>
      </view>
    </u-tabbar>

    <ShippingAddressPop
      ref="addreddPopRef"
      :show.sync="shippingAddressShow"
      @setAddress="setAddress"
    >
    </ShippingAddressPop>
  </view>
</template>

<script>
import CheckedCircle from "@/components/checked-circle/index.vue";
import ShippingAddressPop from "@/subpages/components/shippingAddressPop/index.vue";
import {
  fetchShoppingCartList,
  fetchOrderCreate,
  fetchShoppingCartDelete,
} from "@/services/api";
import { mapActions, mapGetters } from "vuex";
export default {
  components: {
    CheckedCircle,
    ShippingAddressPop,
  },
  data() {
    return {
      value: 1,
      cartInfo: {
        total: 0,
      },
      cartList: [],
      deadlineList: [],
      // 勾选的商品信息
      checked: [],
      isEdit: false,
      checkedAll: [],
      // 地址信息
      address: {},
      shippingAddressShow: false,
    };
  },
  onLoad() {
    this.getCartList();
  },
  methods: {
    ...mapActions("goods", ["updateShoppingCartNum"]),
    //获取购物车列表
    async getCartList() {
      const { data, error } = await fetchShoppingCartList({
        quantity: 1,
      });
      if (!error) {
        this.cartList =
          data?.map((item) => ({
            ...item,
            goodsSkuInfo: JSON.parse(item.goodsSkuInfo),
          })) || [];
        this.updateShoppingCartNum(data.length);
        this.cartInfo.total = data.length;
        // 默认选择所有商品
        this.checkedAll = [true];
        this.checked = this.cartList.map((item) => item.serialNo);
      }
    },
    // 清空失效的商品
    onRemoveDeadline() {
      console.log("清空失效的商品");
    },
    // 确认提交
    async onConfirm() {
      console.log("确认提交");
      if (!this.checked.length) {
        uni.$u.toast("请勾选商品");
        return;
      }
      if (!this.address?.serialNo) {
        uni.$u.toast("请选择收货地址");
        return;
      }
      const goodsList = this.cartList
        .filter((item) => this.checked.includes(item.serialNo))
        .map((item) => {
          return {
            ...item,
            goodsImage: item.coverImage,
            goodsSkuInfo: JSON.stringify(item.goodsSkuInfo),
            // 规格id可能有问题
            goodsSkuNo: item.skuNo,
            quantity: item.quantity + "",
          };
        });
      const { data, error } = await fetchOrderCreate({
        type: "2",
        source: "wxapp",
        deliveryAddressNo: this.address?.serialNo,
        remark: "购物车统一下单",
        goodsList,
      });
      if (!error) {
        const { error: deleteError } = await fetchShoppingCartDelete({
          shoppingCartNoList: this.checked,
        });
        this.getCartList();

        console.log(data.serialNo);
        this.$Router.push({
          name: "orderConfirm",
          params: {
            serialNo: data.serialNo,
          },
        });
      }
    },
    // 确认删除
    onRemove() {
      const that = this;
      uni.showModal({
        content: "确定删除？",
        success: async (res) => {
          const { data, error } = await fetchShoppingCartDelete({
            shoppingCartNoList: this.checked,
          });
          if (!error) {
            uni.$u.toast("删除成功");
            that.getCartList();
          }
        },
      });
    },
    // 全部选中/取消全选
    onCheckAll(val) {
      console.log("有变化", val);
      if (val.length) {
        this.checked = this.cartList.map((item) => item.serialNo);
      } else {
        this.checked = [];
      }
      console.log("现在的是", this.checked);
    },
    // 选中某些项
    onCheckItem(val) {
      if (val.length == this.cartList.length) {
        this.checkedAll = [true];
      } else {
        this.checkedAll = [];
      }
      console.log("现在的是", val, this.checkedAll);
    },
    // 去选择商品
    onHome() {
      uni.switchTab({
        url: "/pages/index/index",
      });
    },
    // 选择地址
    setAddress(val) {
      console.log(val);
      this.address = val;
    },
    selectShopAddress() {
      this.shippingAddressShow = true;
    },
  },
  computed: {
    ...mapGetters("goods", { shoppingCartNum: "getShoppingCartNum" }),
    totalAmount() {
      return this.cartList.reduce((total, item) => {
        return (
          total +
          (this.checked.includes(item.serialNo)
            ? item.price * item.quantity
            : 0)
        );
      }, 0);
    },
  },
};
</script>
<style>
page {
  background-color: #f5f6f7;
}
</style>
<style lang="scss" scoped>
.goods-card {
  background: #fff;
}

.spec-box {
  height: 60rpx;
  width: 300rpx;
  background: #fafafa;
  border-radius: 30rpx;
}

.invalidGoods {
  background: #fff;
}

.address-div {
  position: absolute;
  top: -10px;
  width: 100%;
  background: white;
  padding-top: 5px;
  padding-left: 10px;
}
</style>
